import { useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppSelector, useAppDispatch } from '@/store';
import {
  login as loginAction,
  register as registerAction,
  logout as logoutAction,
  getCurrentUser,
  updateProfile,
  clearError,
} from '@/store/slices/authSlice';
import { showToast } from '@/store/slices/uiSlice';
import { LoginCredentials, RegisterData, User } from '@/types/auth';
import { windowService } from '@/services/window';

export const useAuth = () => {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { user, isAuthenticated, isLoading, error } = useAppSelector(state => state.auth);

  // Login function
  const login = useCallback(
    async (credentials: LoginCredentials) => {
      try {
        const result = await dispatch(loginAction(credentials));

        if (loginAction.fulfilled.match(result)) {
          dispatch(
            showToast({
              type: 'success',
              title: '登录成功',
              message: `欢迎回来，${result.payload.username}！`,
            })
          );

          // 登录成功后设置窗口为可调整大小并最大化
          await windowService.setResizable(true);
          await windowService.maximize();

          navigate('/dashboard');
          return { success: true };
        } else {
          dispatch(
            showToast({
              type: 'error',
              title: '登录失败',
              message: result.payload as string,
            })
          );
          return { success: false, error: result.payload as string };
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '登录失败';
        dispatch(
          showToast({
            type: 'error',
            title: '登录失败',
            message: errorMessage,
          })
        );
        return { success: false, error: errorMessage };
      }
    },
    [dispatch, navigate]
  );

  // Register function
  const register = useCallback(
    async (data: RegisterData) => {
      try {
        const result = await dispatch(registerAction(data));

        if (registerAction.fulfilled.match(result)) {
          dispatch(
            showToast({
              type: 'success',
              title: '注册成功',
              message: `欢迎加入，${result.payload.username}！`,
            })
          );

          // 注册成功后设置窗口为可调整大小并最大化
          await windowService.setResizable(true);
          await windowService.maximize();

          navigate('/dashboard');
          return { success: true };
        } else {
          dispatch(
            showToast({
              type: 'error',
              title: '注册失败',
              message: result.payload as string,
            })
          );
          return { success: false, error: result.payload as string };
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '注册失败';
        dispatch(
          showToast({
            type: 'error',
            title: '注册失败',
            message: errorMessage,
          })
        );
        return { success: false, error: errorMessage };
      }
    },
    [dispatch, navigate]
  );

  // Logout function
  const logout = useCallback(async () => {
    try {
      await dispatch(logoutAction());
      dispatch(
        showToast({
          type: 'info',
          title: '已退出登录',
          message: '感谢您的使用！',
        })
      );

      // 退出登录后设置窗口为不可调整大小
      await windowService.setResizable(false);
      await windowService.setSize(1000, 700);
      await windowService.center();

      navigate('/auth/login');
    } catch (error) {
      // Even if logout fails, clear local state
      navigate('/auth/login');
    }
  }, [dispatch, navigate]);

  // Refresh user data
  const refreshUser = useCallback(async () => {
    try {
      await dispatch(getCurrentUser());
    } catch (error) {
      console.error('Failed to refresh user data:', error);
    }
  }, [dispatch]);

  // Update user profile
  const updateUserProfile = useCallback(
    async (data: Partial<User>) => {
      try {
        const result = await dispatch(updateProfile(data));

        if (updateProfile.fulfilled.match(result)) {
          dispatch(
            showToast({
              type: 'success',
              title: '资料更新成功',
              message: '您的个人资料已更新',
            })
          );
          return { success: true };
        } else {
          dispatch(
            showToast({
              type: 'error',
              title: '更新失败',
              message: result.payload as string,
            })
          );
          return { success: false, error: result.payload as string };
        }
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : '更新失败';
        dispatch(
          showToast({
            type: 'error',
            title: '更新失败',
            message: errorMessage,
          })
        );
        return { success: false, error: errorMessage };
      }
    },
    [dispatch]
  );

  // Clear authentication error
  const clearAuthError = useCallback(() => {
    dispatch(clearError());
  }, [dispatch]);

  // Check if user has specific permission
  const hasPermission = useCallback(
    (permission: string): boolean => {
      if (!user) return false;

      // Basic role-based permissions
      const rolePermissions = {
        admin: [
          'view_analytics',
          'manage_users',
          'system_settings',
          'batch_process',
          'video_edit',
          'export_data',
        ],
        moderator: ['view_analytics', 'batch_process', 'video_edit', 'export_data'],
        user: ['video_edit', 'batch_process'],
      };

      const userPermissions = rolePermissions[user.role as keyof typeof rolePermissions] || [];
      return userPermissions.includes(permission);
    },
    [user]
  );

  // Check if user has any of the specified permissions
  const hasAnyPermission = useCallback(
    (permissions: string[]): boolean => {
      return permissions.some(permission => hasPermission(permission));
    },
    [hasPermission]
  );

  // Check if user has all of the specified permissions
  const hasAllPermissions = useCallback(
    (permissions: string[]): boolean => {
      return permissions.every(permission => hasPermission(permission));
    },
    [hasPermission]
  );

  // Check if user is admin
  const isAdmin = useCallback((): boolean => {
    return user?.role === 'admin';
  }, [user]);

  // Check if user is moderator or admin
  const isModerator = useCallback((): boolean => {
    return user?.role === 'moderator' || user?.role === 'admin';
  }, [user]);

  // Get user's subscription status
  const getSubscriptionStatus = useCallback(() => {
    if (!user?.subscription) return 'free';
    return user.subscription.status;
  }, [user]);

  // Check if user can perform action based on subscription
  const canPerformAction = useCallback(
    (requiredPlan: string): boolean => {
      if (!user) return false;

      const planHierarchy = ['free', 'basic', 'pro', 'enterprise'];
      const userPlan = user.subscription?.plan || 'free';
      const userPlanIndex = planHierarchy.indexOf(userPlan);
      const requiredPlanIndex = planHierarchy.indexOf(requiredPlan);

      return userPlanIndex >= requiredPlanIndex;
    },
    [user]
  );

  return {
    // State
    user,
    isAuthenticated,
    isLoading,
    error,

    // Actions
    login,
    register,
    logout,
    refreshUser,
    updateUserProfile,
    clearAuthError,

    // Permission checks
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    isAdmin,
    isModerator,

    // Subscription
    getSubscriptionStatus,
    canPerformAction,
  };
};
